package cn.workreport.modules.role.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.workreport.modules.common.annotations.UserLoginToken;
import cn.workreport.modules.common.controller.BaseController;
import cn.workreport.modules.common.po.IdsPO;
import cn.workreport.modules.common.po.PagePO;
import cn.workreport.modules.common.vo.PageVO;
import cn.workreport.modules.permission.enums.PermissionEnum;
import cn.workreport.modules.role.entity.Role;
import cn.workreport.modules.role.service.IRoleService;
import cn.workreport.modules.users.entity.UserEntity;
import cn.workreport.util.JsonResult;
import cn.workreport.util.PageQueryUtil;
import cn.workreport.util.UserChacheFromToken;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yyf
 * @since 2022-01-04
 */
@Slf4j
@RestController
@UserLoginToken
@Api(tags = "角色模块")
public class RoleController extends BaseController {

    @Autowired
    private IRoleService roleService;

    /**
     * 保存或修改角色
     *
     * @param entity 实体信息
     * @return 成功与否，成功返回实体信息，失败返回错误信息
     */
    @ApiOperation("修改或保存角色")
    @UserLoginToken(required = true, permission = {PermissionEnum.ROLE_SAVE_OR_UPDATE})
    @PostMapping("/role/saveOrUpdate")
    public JsonResult<?> saveOrUpdate(Role entity) {
        log.info("===> 进入 /role/saveOrUpdate ===> params = " + entity);
        return roleService.saveOrUpdateEntity(entity);
    }

    /**
     * 分页查询角色
     *
     * @param pagePO
     * @return 查询结果
     */
    @ApiOperation("分页查询角色")
    @UserLoginToken(required = true, permission = {PermissionEnum.ROLE_PAGE})
    @PostMapping("/role/listPage")
    public JsonResult<?> listPage(@RequestBody PagePO<Role> pagePO) {
        log.info("===> 进入 /role/listPage ===> params: pagePO=" + pagePO);
        // 如果不是超级管理员，必须要传 orgId
        UserEntity loginUser = UserChacheFromToken.getUser();
        Role condition = pagePO.getCondition();
        if (
                (ObjectUtil.isEmpty(loginUser.getIsSupperAdmin()) || !loginUser.getIsSupperAdmin())
                        && (ObjectUtil.isEmpty(condition) || ObjectUtil.isEmpty(condition.getOrgId()))
        ) {
            return JsonResult.fail("参数 orgId 不能为空");
        }
        // 执行查询
        IPage<Role> page = new PageQueryUtil<Role>().getPage(pagePO);
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        if (!ObjectUtils.isEmpty(condition)) {
            wrapper.like(!ObjectUtils.isEmpty(condition.getRoleName()), Role::getRoleName, condition.getRoleName());
            wrapper.eq(!ObjectUtil.isEmpty(condition.getOrgId()), Role::getOrgId, condition.getOrgId());
        }
        wrapper.orderByDesc(Role::getCreatedTime);
        PageVO<Role> result = roleService.pageEntity(page, wrapper);
        return JsonResult.ok(result);
    }

    /**
     * 根据ID查询角色
     * 如果查询不到，new 一个返回，可以作为新建请求
     *
     * @param id ID
     * @return 查询结果
     */
    @ApiOperation("根据ID查询角色")
    @UserLoginToken(required = true, permission = {PermissionEnum.ROLE_GET_BY_ID})
    @GetMapping("/role/getById")
    public JsonResult<?> getById(Integer id) {
        log.info("===> 进入 /role/getById ===> params = " + id);
        if (ObjectUtil.isEmpty(id)) {
            return JsonResult.fail("参数 id 不能为空");
        }
        Role entity = roleService.getByIdEntity(id);
        return JsonResult.ok(entity);
    }

    /**
     * 批量或单体删除角色
     *
     * @param idsPO ID集合
     * @return 成功与否
     */
    @ApiOperation("批量删除角色")
    @UserLoginToken(required = true, permission = {PermissionEnum.ROLE_DELETE})
    @PostMapping("/role/removeByIds")
    public JsonResult<?> removeByIds(IdsPO idsPO) {
        log.info("===> 进入 /role/removeByIds ===> params = " + idsPO);
        if (ObjectUtils.isEmpty(idsPO)) {
            return JsonResult.fail("ids 不能为空！");
        }
        return roleService.removeByIdsEntity(idsPO.getIds());
    }

    /**
     * 设置角色是否启用
     */
    @ApiOperation("设置角色是否启用")
    @UserLoginToken(required = true, permission = {PermissionEnum.ROLE_TOGGLE_USE})
    @PostMapping("/role/toggleUse")
    public JsonResult<?> toggleUse(Integer id, Boolean asUse) {
        if (ObjectUtils.isEmpty(id)) {
            return JsonResult.fail("id 不能为空！");
        }
        if (ObjectUtils.isEmpty(asUse)) {
            return JsonResult.fail("asUse 不能为空！");
        }
        return roleService.toggleUse(id, asUse);
    }

    /**
     * 查询已启用的所有角色列表
     *
     * @return 查询结果
     */
    @ApiOperation("查询已启用的所有角色列表")
    @UserLoginToken(permission = {PermissionEnum.ROLE_PAGE})
    @GetMapping("/role/getEnableList")
    public JsonResult<?> getEnableList(Integer orgId) {
        log.info("===> 进入 /role/getEnableList ===> params: orgId=" + orgId);
        if (ObjectUtil.isEmpty(orgId)) {
            return JsonResult.fail("参数 orgId 不能为空");
        }
        List<Role> result = roleService.getEnableList(orgId);
        return JsonResult.ok(result);
    }

    /**
     * 获取初始化的角色名列表
     *
     * @return 角色名列表
     */
     @ApiOperation("获取初始化的角色名列表")
     @GetMapping("/role/listInitRoleName")
     public JsonResult<?> listInitRoleName() {
       log.info("===> 进入 /role/listInitRoleName ===>");
       List<String> initRoleNameList = roleService.listInitRoleName();
       return JsonResult.ok(initRoleNameList);
     }

}
